<!-- chat.html -->
{% extends 'blog_base.html' %}
{% block title %}
	博客首页
{% endblock %}

{% block main%}
    <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户对话界面</title>
    <!-- 引入Bootstrap 5 CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* 自定义样式 */
        .chat-container {
            max-width: 800px;
            margin: 20px auto;
            border: 1px solid #ddd;
            border-radius: 10px;
            background-color: #f8f9fa;
        }

        .messages-container {
            height: 60vh;
            overflow-y: auto;
            padding: 20px;
            background-color: white;
        }

        .message {
            display: flex;
            margin-bottom: 15px;
            animation: fadeIn 0.3s ease-in;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 15px;
        }

        .message-content {
            flex-grow: 1;
            max-width: 80%;
        }

        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }

        .message-username {
            font-weight: bold;
            margin-right: 10px;
        }

        .message-time {
            color: #6c757d;
            font-size: 0.8em;
        }

        .message-text {
            background-color: #e9ecef;
            padding: 10px;
            border-radius: 10px;
            word-break: break-word;
        }

        .input-container {
            padding: 20px;
            border-top: 1px solid #ddd;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 移动端适配 */
        @media (max-width: 768px) {
            .messages-container {
                height: 70vh;
            }

            .message-content {
                max-width: 90%;
            }
        }
    </style>
</head>
<body>
    <!-- 对话容器 -->
    <div class="chat-container">
        <!-- 消息展示区域 -->
        <div class="messages-container" id="messagesContainer">
            <!-- 示例消息 -->
            <div class="message">
                <img src="avatars/default.png" class="message-avatar" alt="用户头像">
                <div class="message-content">
                    <div class="message-header">
                        <span class="message-username">张三</span>
                        <span class="message-time">2023-07-20 14:30</span>
                    </div>
                    <div class="message-text">
                        大家好！这是我的第一条留言，这个博客系统看起来很棒！
                    </div>
                </div>
            </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="input-container">
            <div class="input-group">
                <textarea
                    id="messageInput"
                    class="form-control"
                    placeholder="输入消息..."
                    rows="2"
                    maxlength="500"
                ></textarea>
                <button id="sendButton" class="btn btn-primary">
                    <span class="d-none d-md-inline">发送</span>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-send d-md-none" viewBox="0 0 16 16">
                        <path d="M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11zM6.636 10.07l2.761 4.338L14.13 2.576 6.636 10.07zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493z"/>
                    </svg>
                </button>
            </div>
            <div id="charCount" class="text-end text-muted mt-1">0/500</div>
        </div>
    </div>

    <script>
        // DOM元素引用
        const messagesContainer = document.getElementById('messagesContainer');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const charCount = document.getElementById('charCount');

        // 模拟当前用户信息（实际应从后端获取）
        const currentUser = {
            username: '当前用户',
            avatar: 'avatars/default.png'
        };

        // 输入框实时字数统计
        messageInput.addEventListener('input', function() {
            charCount.textContent = `${this.value.length}/500`;
        });

        // 发送消息处理函数
        async function sendMessage() {
            const messageText = messageInput.value.trim();

            if (!messageText) {
                messageInput.focus();
                return;
            }

            try {
                // 模拟发送到后端API
                const response = await fetch('/api/messages/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{% csrf_token %}' // Django CSRF令牌
                    },
                    body: JSON.stringify({
                        content: messageText
                    })
                });

                if (response.ok) {
                    // 清空输入框
                    messageInput.value = '';
                    charCount.textContent = '0/500';

                    // 添加消息到界面（实际应使用返回的数据）
                    addMessageToUI({
                        username: currentUser.username,
                        avatar: currentUser.avatar,
                        content: messageText,
                        timestamp: new Date().toISOString()
                    });
                }
            } catch (error) {
                console.error('发送失败:', error);
                alert('消息发送失败，请稍后重试');
            }
        }

        // 添加消息到界面
        function addMessageToUI(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message';

            messageElement.innerHTML = `
                <img src="${message.avatar}" class="message-avatar" alt="${message.username}的头像">
                <div class="message-content">
                    <div class="message-header">
                        <span class="message-username">${message.username}</span>
                        <span class="message-time">${formatTime(message.timestamp)}</span>
                    </div>
                    <div class="message-text">${escapeHtml(message.content)}</div>
                </div>
            `;

            messagesContainer.appendChild(messageElement);
            // 滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 事件监听
        sendButton.addEventListener('click', sendMessage);
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 工具函数：格式化时间
        function formatTime(isoString) {
            const date = new Date(isoString);
            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
        }

        // 工具函数：防止XSS攻击
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
    </script>
</body>
</html>
{% endblock %}